'use strict';
const {appId, appSecret, getToken} = require("wx-common");

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	
	//jscode2session
	
	const {code} = event;
	
	const db = uniCloud.database()
	
	
	const res = await uniCloud.httpclient.request("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code",
		{
			dataType:"json"
		})
	
	const openid = res.data.openid;
	
	let dbRes = await db.collection("users").where({
		openid:openid
	}).limit(1).get();//先获取一下数据库是否有该数据，再确定添加，否则不添加，直接返回
	
	let userData
	const token = getToken(openid);
	if(dbRes.affectedDocs <= 0){//数据库里没有该数据
		
		console.log(res);
		
		userData = {
			openid:openid,
			nickName:"微信用户",
			avatarUrl:""
		}
		
		await db.collection("users").add(userData)
	}else{
		userData = dbRes.data[0];
	}
	
	delete userData["openid"]//不能在返回数据里包含openid，openid是隐私信息，只有本人知道，其他人不能知道
	userData['token'] = token;
	
	
	//返回数据给客户端
	return userData;
};
